package com.wn.pettyloan.security;


import com.wn.pettyloan.security.emp.*;
import com.wn.pettyloan.security.user.LoginAuthenticationFailureHandler;
import com.wn.pettyloan.security.user.LoginAuthenticationSuccessHandler;
import com.wn.pettyloan.security.user.LoginFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * @program: pettyloan
 * @ClassName SecurityConfig
 * @description:
 * @author: 韩旭
 * @create: 2022-12-15 14:29
 **/
@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    @Qualifier("empDetailsServiceImpl")
    private UserDetailsService userDetailsService1;

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService2;



    @Autowired
    private JWTLogoutSuccessHandler jwtLogoutSuccessHandler;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;

    /**
     * 解决 无法直接注入 AuthenticationManager
     */
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    EmpLoginAuthenticationSuccessHandler empLoginAuthenticationSuccessHandler() {
        return new EmpLoginAuthenticationSuccessHandler();
    }

    @Bean
    EmpLoginAuthenticationFailureHandler empLoginAuthenticationFailureHandler() {
        return new EmpLoginAuthenticationFailureHandler();
    }

    //认证成功处理器
    @Bean
    LoginAuthenticationSuccessHandler loginAuthenticationSuccessHandler() {
        return new LoginAuthenticationSuccessHandler();
    }

    //认证失败处理器
    @Bean
    LoginAuthenticationFailureHandler loginAuthenticationFailureHandler() {
        return new LoginAuthenticationFailureHandler();
    }

    //员工
    @Bean
    EmpLoginFilter emploginFilter() throws Exception {
        EmpLoginFilter emploginFilter = new EmpLoginFilter();
        emploginFilter.setAuthenticationManager(authenticationManager());
        emploginFilter.setAuthenticationSuccessHandler(empLoginAuthenticationSuccessHandler());
        emploginFilter.setAuthenticationFailureHandler(empLoginAuthenticationFailureHandler());

        return emploginFilter;
    }

    //用户自定义处理器
    @Bean
    LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        //指定AuthenticationManager，注意不是上面带bean的方法
        loginFilter.setAuthenticationManager(authenticationManager());

        //登录成功的处理
        loginFilter.setAuthenticationSuccessHandler(loginAuthenticationSuccessHandler());
        //登录失败的处理
        loginFilter.setAuthenticationFailureHandler(loginAuthenticationFailureHandler());
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // CRSF禁用，不使用session
        httpSecurity.csrf().disable();
        //允许跨域
        httpSecurity.cors();
        // 基于token，所以不需要session
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 过滤请求

//        httpSecurity.authorizeRequests().anyRequest().permitAll();

        httpSecurity.exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);
        httpSecurity.authorizeRequests()
                .antMatchers("/*/login").permitAll()//注意不能使用.anonymous(),否则登录成功再点登录时一直提示403
//                .antMatchers("").hasAnyRole("管理员")
                .anyRequest().permitAll();




//        httpSecurity.authorizeRequests()
//                .antMatchers("/emp/login").permitAll()//注意不能使用.anonymous(),否则登录成功再点登录时一直提示403
//                //.antMatchers("/users/*").hasAnyRole("管理员")
//                .anyRequest().authenticated();




        // 添加loginFilter,让其替换UsernamePasswordAuthenticationFilter过滤器执行
        httpSecurity.addFilterAt(emploginFilter(), UsernamePasswordAuthenticationFilter.class);
        // 添加loginFilter,在UsernamePasswordAuthenticationFilter过滤器所在位置添加
        httpSecurity.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
        //退出成功
        httpSecurity.logout().logoutSuccessHandler(jwtLogoutSuccessHandler);
        // 添加JWTfilter,让其在UsernamePasswordAuthenticationFilter过滤器之前执行
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);


    }


    /**
     * 强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    /**
     * 身份认证接口
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService1).passwordEncoder(bCryptPasswordEncoder());
        auth.userDetailsService(userDetailsService2).passwordEncoder(bCryptPasswordEncoder());
    }
}